<script>

import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";

export default {
  name: "UserView",

  inject: ['reload'],

  data() {
    return {
      //用户列表数据，初始值为空
      userList: [{}],
      //每页显示多少条数据
      pageSize: 0,
      //总共查询多少数据
      total: 0,

      //新增用户的弹窗
      userDialogVisible: false,

      //定义用户表单对象，初始值为空
      userQury: {},

      //定义用户验证规则
      userRules: {
        loginAct: [
          {required: true, message: "请输入账号", trigger: "blur"}
        ],

        loginPwd: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 6, message: "密码长度至少为6位！！"}
        ],

        name: [
          {required: true, message: "请输入姓名", trigger: "blur"},
          {pattern: /^[\u4E00-\u9FA5]{1,5}$/, message: "姓名必须为中文", trigger: "blur"},
        ],

        phone: [
          {required: true, message: "请输入手机号", trigger: "blur"},
          {pattern: /^1[34578]\d{9}$/, message: "请输入正确的手机号", trigger: "blur"},
        ],

        email: [
          {required: true, message: "请输入邮箱", trigger: "blur"},
          {
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            message: "请输入正确的邮箱",
            trigger: "blur"
          },
        ],

        accountNoExpired: [
          {required: true, message: "请选择账号是否过期", trigger: "blur"}
        ],

        credentialsNoExpired: [
          {required: true, message: "请选择密码是否过期", trigger: "blur"}
        ],

        accountNoLocked: [
          {required: true, message: "请选择账号是否锁定", trigger: "blur"}
        ],

        accountEnabled: [
          {required: true, message: "请选择账号是否开启", trigger: "blur"}
        ],
      },

      //下拉选项数组
      options: [
        {label: "是", value: 1},
        {label: "否", value: 0},
      ],

      //用户id数组
      userIdArray: [],
    }
  },

  methods: {
    //勾选时触发该函数
    handleSelectionChange(selectionDataArray) {
      console.log(selectionDataArray);
      this.userIdArray = []
      selectionDataArray.forEach(data => {
        let userId = data.id
        this.userIdArray.push(userId);
      })
    },

    //查询用户列表数据
    getData(current) {
      doGet("/api/users", {
        current: current  //当前页
      }).then(resp => {
        if (resp.data.code == 200) {
          this.userList = resp.data.data.list;
          this.total = resp.data.data.total;
          this.pageSize = resp.data.data.pageSize;
        }
      })
    },

    //分页函数
    toPage(current) {
      this.getData(current);
    },

    //用户详情
    view(id) {
      console.log(id);
      //跳转路由/dashboard/user/1
      this.$router.push("/dashboard/user/" + id);
    },

    //添加用户
    add() {
      this.userQury = {};
      this.userDialogVisible = true;
    },

    //用户提交保存
    userSubmit() {
      let formData = new FormData();
      for (let field in this.userQury) {
        formData.append(field, this.userQury[field])
      }
      this.$refs.userReForm.validate((isValid) => {
        if (isValid) {
          // 编辑
          if (this.userQury.id > 0) {
            doPut("/api/user", formData).then(resp => {
              if (resp.data.code == 200) {
                messageTip("更新用户成功", "success")
                //实现页面刷新
                this.reload();
              } else {
                messageTip("更新用户失败", "error")
              }
            })
          } else {
            //新增
            doPost("/api/user", formData).then(resp => {
              if (resp.data.code == 200) {
                messageTip("新增用户成功", "success")
                //实现页面刷新
                this.reload();
              } else {
                messageTip("新增用户失败", "error")
              }
            })
          }
        }
      })
    },

    //编辑用户
    edit(id) {
      this.userDialogVisible = true;
      this.loadUser(id);
    },

    //加载数据
    loadUser(id) {
      doGet("/api/user/" + id, {}).then((resp) => {
        if (resp.data.code == 200) {
          this.userQury = resp.data.data;
          this.userQury.loginPwd = ""
        }
      })
    },

    //删除用户
    del(id) {
      messageConfirm("确定要删除吗?").then(() => {
        doDelete("/api/user/" + id, {}).then(resp => {
          if (resp.data.code == 200) {
            messageTip("删除用户成功", "success")
            //实现页面刷新
            this.reload();
          } else {
            messageTip("删除用户失败，原因: " + resp.data.msg, "error")
          }
        })
      }).catch(() => {
        messageTip("取消删除用户", "warning")
      })
    },

    //批量删除
    batchDel() {
      if (this.userIdArray.length <= 0) {
        messageTip("请选择要删除的数据", "warning")
        return;
      }
      messageConfirm("确定要删除这些数据吗?").then(() => {
        //数组变为字符串
        let ids = this.userIdArray.join(",")
        doDelete("/api/user", {
          ids: ids
        }).then(resp => {
          if (resp.data.code == 200) {
            messageTip("批量删除用户成功", "success")
            //实现页面刷新
            this.reload();
          } else {
            messageTip("批量删除用户失败，原因: " + resp.data.msg, "error")
          }
        })
      }).catch(() => {
        messageTip("取消批量删除用户", "warning")
      })
    },
  },

  mounted() {
    this.getData(1);
  }
}

</script>

<template>
  <el-button type="primary" @click="add()" v-has-permission="'user:add'">添加用户</el-button>
  <el-button type="danger" @click="batchDel()" v-has-permission="'user:delete'">批量删除</el-button>

  <!--用户数据展示-->
  <el-table
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55"/>
    <el-table-column type="index" label="序号" width="60"/>
    <el-table-column property="loginAct" label="账号"/>
    <el-table-column property="name" label="姓名" show-overflow-tooltip/>
    <el-table-column property="phone" label="手机" show-overflow-tooltip/>
    <el-table-column property="email" label="邮箱" show-overflow-tooltip/>
    <el-table-column property="createTime" label="创建时间" show-overflow-tooltip/>
    <el-table-column label="操作" width="240">
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)" v-has-permission="'user:view'">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)" v-has-permission="'user:edit'">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)" v-has-permission="'user:delete'">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--导航分页-->
  <el-pagination background
                 layout="prev, pager, next"
                 :total="total"
                 :page-size="pageSize"
                 @prev-click="toPage"
                 @next-click="toPage"
                 @current-change="toPage"
  />

  <!--新增用户的弹窗-->
  <el-dialog v-model="userDialogVisible" :title="userQury.id > 0 ?'编辑用户':'添加用户'" width="55%" center draggable>

    <el-form ref="userReForm" :model="userQury" label-width="110px" :rules="userRules">
      <el-form-item label="账号" prop="loginAct">
        <el-input v-model="userQury.loginAct"/>
      </el-form-item>

      <!--编辑-->
      <el-form-item label="密码" v-if="userQury.id>0">
        <el-input v-model="userQury.loginPwd" type="password"/>
      </el-form-item>

      <!--新增-->
      <el-form-item label="密码" prop="loginPwd" v-else>
        <el-input v-model="userQury.loginPwd" type="password"/>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="userQury.name"/>
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input v-model="userQury.phone"/>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userQury.email"/>
      </el-form-item>

      <el-form-item label="账号未过期" prop="accountNoExpired">
        <el-select v-model="userQury.accountNoExpired" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="密码未过期" prop="credentialsNoExpired">
        <el-select v-model="userQury.credentialsNoExpired" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="账号未锁定" prop="accountNoLocked">
        <el-select v-model="userQury.accountNoLocked" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="账号是否开启" prop="accountEnabled">
        <el-select v-model="userQury.accountEnabled" placeholder="请选择">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>


    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userDialogVisible = false">关 闭</el-button>
        <el-button type="primary" @click="userSubmit()">提 交</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<style scoped>

.el-button {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 12px;
}
</style>